#include "lib_MonitorMem.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

MonitorMem::MonitorMem()
{
}

MonitorMem::~MonitorMem()
{
}

sysMem_t* MonitorMem::update_sys_mem()
{
    FILE* fp = fopen(FILE_PROCFS_MEMINFO, "r");
    if (fp == NULL)
    {
        printf("open %s failed\n", FILE_PROCFS_MEMINFO);
        return NULL;
    }

    char* start_str;
    char buf[128];
    while (fgets(buf, sizeof(buf) - 1, fp) != NULL)
    {
        if (strncmp(buf, "MemTotal:", 9) == 0)
        {
            start_str = strchr(buf, ':') + 1;
            sysMem_.total = strtoul(start_str, NULL, 10);
        }
        else if (strncmp(buf, "MemFree:", 8) == 0)
        {
            start_str = strchr(buf, ':') + 1;
            sysMem_.free = strtoul(start_str, NULL, 10);
        }
        else if (strncmp(buf, "Buffers:", 8) == 0)
        {
            start_str = strchr(buf, ':') + 1;
            sysMem_.buff = strtoul(start_str, NULL, 10);
        }
        else if (strncmp(buf, "Cached:", 7) == 0)
        {
            start_str = strchr(buf, ':') + 1;
            sysMem_.cached = strtoul(start_str, NULL, 10);
            break;
        }
    }
    fclose(fp);

    // 注意：结构体中的内存值是以 "内存单元" 数量表示的，需要乘以 mem_unit 转换为字节
    sysMem_.used = sysMem_.total - sysMem_.free - sysMem_.buff - sysMem_.cached;
    sysMem_.mem_percent = float(sysMem_.used) / sysMem_.total * 100.0;

    return &sysMem_;
}

unsigned long long MonitorMem::get_total_mem()
{
    return sysMem_.total;
}

void MonitorMem::show_sys_mem(sysMem_t* sysMem)
{
    printf("MB total:%5.2f used:%5.2f free:%5.2f buff:%5.2f cached:%5.2f usage:%5.2f\n",
        sysMem->total / 1024.0,
        sysMem->used / 1024.0,
        sysMem->free / 1024.0,
        sysMem->buff / 1024.0,
        sysMem->cached / 1024.0,
        sysMem->mem_percent
    );
}